package cn.ruc.dbiir.storm.generator.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

public class DBUtil {
	
	public static Connection getConn(String db_url, String db_user, String db_pwd)
	{
		Connection conn = null;

		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (ClassNotFoundException e1)
		{
			e1.printStackTrace();
		}

		try
		{
			conn = DriverManager.getConnection(db_url, db_user, db_pwd);
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}

		return conn;
	}

	public static void freeConn(Connection conn)
	{
		try
		{
			if (conn != null)
				conn.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}

	}
	
	
	public static PreparedStatement getPStatement(Connection conn,String sql) {
		PreparedStatement pstat = null;
		try
		{
			pstat = conn.prepareStatement(sql);
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		return pstat;
	}
	
	
	public static void addToBatch(PreparedStatement pstat,String ymd,int fuin,int amt, Long ts){
		try
		{
			pstat.setInt(1, amt);
			pstat.setInt(2, Integer.parseInt(ymd));
			pstat.setInt(3, amt);
			pstat.setInt(4, amt);
			pstat.setTimestamp(5, new Timestamp(ts));
			pstat.setInt(6, fuin);
			pstat.addBatch();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void executeBatch(PreparedStatement pstat) {
		try {
			pstat.executeBatch();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	public static void setAutoCommit(Connection conn,boolean autoCommit) {
		try {
			conn.setAutoCommit(autoCommit);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void commitTrans(Connection conn) {
		try {
			conn.commit();
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
}
